from datetime import datetime

from rest_framework.permissions import AllowAny
from rest_framework_jwt.views import JSONWebTokenAPIView
from rest_framework_jwt.serializers import JSONWebTokenSerializer
from django.contrib.auth import authenticate
from rest_framework import serializers
from django.utils.translation import ugettext as _
from rest_framework_jwt.settings import api_settings
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

class AdminJSONWebTokenSerializer(JSONWebTokenSerializer):

    def validate(self, attrs):
        credentials = {
            self.username_field: attrs.get(self.username_field),
            'password': attrs.get('password')
        }

        if all(credentials.values()):
            user = authenticate(**credentials)

            if user:
                user.last_login = datetime.now()
                user.save()
                if not user.is_active:
                    msg = _('User account is disabled.')
                    raise serializers.ValidationError(msg)
                 # 新增添加
                if not user.is_superuser:
                    if not user.is_staff:
                        msg = _('User account is disabled.')
                        raise serializers.ValidationError(msg)
                #     user.username = '运营员工'
                # if user.username != '运营员工':
                #     user.username = '超级管理员'
                payload = jwt_payload_handler(user)
                return {
                    'token': jwt_encode_handler(payload),
                    'user': user
                }
            else:
                msg = _('Unable to log in with provided credentials.')
                raise serializers.ValidationError(msg)
        else:
            msg = _('Must include "{username_field}" and "password".')
            msg = msg.format(username_field=self.username_field)
            raise serializers.ValidationError(msg)

class AdminJsonWebTokenAPIView(JSONWebTokenAPIView):
    permission_classes = [AllowAny]
    serializer_class = AdminJSONWebTokenSerializer

